<script setup>
import { ref, onMounted, onUnmounted, reactive, nextTick } from 'vue'
import {
  Modal as AModal,
  Button as AButton,
  Tree as ATree,
  message,
  Spin as ASpin,
  Empty as AEmpty
} from 'ant-design-vue'

import { executeTrialCalculation, executeAllocation } from '@/api/claim'
import { DraggableModal } from '@/components/draggable-modal'
const emit = defineEmits(['updateRefreshTable', 'updateVisible', 'updateTable'])

const simpleImage = AEmpty.PRESENTED_IMAGE_SIMPLE
const intervalDuration = 30000 // 每30秒钟调用一次
let Timer = null
function clearTimer() {
  if (Timer) {
    clearInterval(Timer) // 清除轮询
    Timer = null
  }
}
const spinning = ref(false)
const loadingTip = ref('本次试算预计花费3-5分钟,请耐心等待')

const props = defineProps({
  trialParams: {
    type: Object,
    required: true
  }
})
const trialLoading = ref(false)

function handleCancel() {
  trialModalVisible.value = false
  console.log('111', 111)
  emit('updateVisible', false)
}
// 获取treeData
let title = ref('试算待分配')
let description = ref('暂无数据')
const treeArray = reactive([])
async function getTreeData() {
  let res = null
  spinning.value = true
  try {
    res = await executeTrialCalculation(props.trialParams)
  } catch (err) {
    clearTimer()
  }
  if (res?.success == '0') {
    spinning.value = false
    title.value = res.data.overallHierarchyTitle || '试算待分配'
    description.value = res.data.errMessage || '暂无数据'
    const treeList = res.data.treeList || []
    treeList.forEach((tree) => {
      const treeData = [tree]
      const checkedKeys = recursionKey(treeData, [])
      treeArray.push({
        treeData,
        checkedKeys
      })
    })
    emit('updateTable')
    clearTimer()
  } else {
    Timer = setTimeout(() => {
      getTreeData()
    }, intervalDuration)
  }
  console.log('res', res)
}
const trialModalVisible = ref(false)
onMounted(async () => {
  await nextTick()
  trialModalVisible.value = true
  getTreeData()
})
onUnmounted(() => {
  clearTimer()
})
function recursionKey(treeData, keyArr = []) {
  for (let i = 0; i < treeData.length; i++) {
    const key = treeData[i].key
    keyArr.push(key)
    if (treeData[i].children && treeData[i].children.length > 0) {
      recursionKey(treeData[i].children, keyArr)
    }
  }
  return keyArr
}

async function handleTrial() {
  trialLoading.value = true
  const checkedKeys = treeArray.map((tree) => tree.checkedKeys)
  let res = null
  const data = {
    keyList: checkedKeys.flat()
  }
  try {
    res = await executeAllocation(data)
  } catch (err) {
    console.log('err', err)
  } finally {
    trialLoading.value = false
  }
  if (res?.success == '0') {
    message.success(res.data.message).then(() => {
      handleCancel()
      emit('updateRefreshTable')
    })
  }
}
</script>
<template>
  <DraggableModal v-model:open="trialModalVisible" width="800px" :title="title">
    <template #footer>
      <a-button key="back" @click="handleCancel">关闭</a-button>
      <a-button
        key="submit"
        type="primary"
        :disabled="spinning"
        :loading="trialLoading"
        @click="handleTrial"
        >执行分配</a-button
      >
    </template>
    <a-spin :spinning="spinning" size="large">
      <template v-slot:tip>
        <span class="loading-tip">
          {{ loadingTip }}
        </span>
      </template>
      <div class="tree-box">
        <div v-if="treeArray.length > 0">
          <div class="tree-item" v-for="(tree, index) in treeArray" :key="index">
            <a-tree
              v-model:checkedKeys="tree.checkedKeys"
              :defaultExpandAll="true"
              checkable
              :tree-data="tree.treeData"
            >
              <template #title="{ title, key, isColorChange }">
                <span :class="{ 'tree-tip': isColorChange }">{{ title }}</span>
              </template>
            </a-tree>
          </div>
        </div>
        <a-empty v-else :image="simpleImage" :description="description" />
      </div>
    </a-spin>
  </DraggableModal>
</template>
<style scoped lang="scss">
.tree-box {
  background: #f5f5f5;
  overflow: scroll;
  white-space: nowrap;
  min-height: 200px;
  max-height: 600px;
  .tree-item {
    display: inline-block;
    width: 350px;
    padding: 10px;
  }
}
.loading-tip {
  color: $danger-color;
  font-size: 14px;
}
.tree-tip {
  color: $danger-color;
}
</style>
